//
//  ChangeAvatarViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/11/7.
//

import UIKit
import SwiftyJSON
import Toast_Swift
import Alamofire
import AlamofireImage

class ChangeAvatarViewController: UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    
    @IBOutlet weak var uploadProgress: UIProgressView!
    var userHeadPortraitUrl:String?
    var userImg:UIImage?
    @IBOutlet weak var userHeadPortraitBtn: UIButton!
    
    @IBAction func changeUserHeadPortrait(_ sender: Any) {
        let alert = UIAlertController.init(title: "", message: "请选择", preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in
            return
        })
        alert.addAction(cancelAction)
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
            let camaraAction = UIAlertAction.init(title: "拍照", style: .default, handler: { (action) in
                if UtilManager.sharedInstance.cameraPermissions(){
                    
                    let imagePickerController:UIImagePickerController = UIImagePickerController()
                    imagePickerController.delegate = self
                    imagePickerController.allowsEditing = false//true为拍照、选择完进入图片编辑模式
                    imagePickerController.sourceType = .camera
                    self.present(imagePickerController, animated: true,completion: nil)
                    
                }else{
                    self.view.makeToast("请打开摄像头权限", duration: 1.0, position: .center)
                }
                
            })
            alert.addAction(camaraAction)
        }
        
        let albumAction = UIAlertAction.init(title: "从相册中选择", style: .default, handler: { (action) in
            if UtilManager.sharedInstance.cameraPermissions(){
                
                let photoPicker =  UIImagePickerController()
               photoPicker.delegate = self
               photoPicker.allowsEditing = true
               photoPicker.sourceType = .photoLibrary
               //在需要的地方present出来
               self.present(photoPicker, animated: true, completion: nil)
                
            }else{
                self.view.makeToast("请在设置中打开相册权限", duration: 1.0, position: .center)
                return
            }
            
        })
        alert.addAction(albumAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    // MARK: - UIImagePikerDelegate
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        userImg = (info[UIImagePickerController.InfoKey.originalImage]! as! UIImage)
        userHeadPortraitBtn.setImage(userImg, for: .normal)
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    func uploadUserHeadPortrait(image: UIImage) {
        uploadProgress.isHidden = false
        
        let data: Data = UtilManager.sharedInstance.cropImage(image: image, ratio: 1).pngData()!
        
        APIManager.sharedInstance.uploadFileRequest(fileData: data) { (progress) in
            DispatchQueue.main.asyncAfter(deadline: .now()) { self.uploadProgress.progress = Float(progress) }
        } completion: { (result, error) in
            if error == nil {
                print("图片url：\(result)")
                self.userHeadPortraitUrl = "\(result)"
                self.goToSubmit()
            }
            DispatchQueue.main.asyncAfter(deadline: .now()) { self.uploadProgress.isHidden = true }
        }
    }
    
    @IBAction func submit(_ sender: Any) {
        if let img = userImg {
            uploadUserHeadPortrait(image: img)
        } else {
            self.view.makeToast("请上传或选择图片", duration: 1.0, position: .center)
        }
    }
    
    func goToSubmit() {
        
        var params = JSON.init(parseJSON: "{}")
        params["avatar"].string = userHeadPortraitUrl

        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.change_user_info_action, method: HTTPMethod.post, params: params) { (result, error) in
            if error == nil {
                var newData:[String:Any] = [:]
                newData["userAvatar"] = self.userHeadPortraitUrl
                UserInfo.sharedInstance.save(dic: newData)
                self.view.makeToast("修改成功", duration: 1.0, position: .center)
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        let font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
        let textAttributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:AppConfig.sharedInstance.MAIN_TITLE_COLOR]
        self.navigationController?.navigationBar.titleTextAttributes = textAttributes
        self.navigationController?.navigationBar.tintColor = AppConfig.sharedInstance.MAIN_TITLE_COLOR
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
        let textAttributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:UIColor.white]
        self.navigationController?.navigationBar.titleTextAttributes = textAttributes
        self.navigationController?.navigationBar.tintColor = UIColor.white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        userHeadPortraitBtn.contentHorizontalAlignment = .fill
        userHeadPortraitBtn.contentVerticalAlignment = .fill
        userHeadPortraitBtn.imageView?.contentMode = .scaleAspectFill
        userHeadPortraitBtn.layer.masksToBounds = true
        userHeadPortraitBtn.layer.cornerRadius = userHeadPortraitBtn.bounds.width/2

        if UserInfo.sharedInstance.userAvatar != "" {
            userHeadPortraitBtn.af.setImage(for: .normal, url: URL(string: UserInfo.sharedInstance.userAvatar)!)
        } else {
            userHeadPortraitBtn.setBackgroundImage(UIImage.init(named: "logo"), for: .normal)
        }
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
